﻿using nblTool.utils;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
using Communication;
using Jn698._45GWTool.Communication;
using Jn698._45GWTool.Models;
using CommonServiceLocator;
using Jn698._45GWTool.ModelViews;
using WebFirst.Entities;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Windows;

namespace _698._45Tool.Utils
{
    internal class TcpHelper
    {
        private static TcpHelper instance = new TcpHelper();
        private Dictionary<string,GPRSInfo> GPRSDevices = new Dictionary<string,GPRSInfo>();
        public bool isComplete = false;

        /// <summary>
        /// 串口状态
        /// </summary>
        public ServerState Status => service.ServerState;

        /// <summary>
        /// 自定义串口消息接收事件
        /// </summary>
        public event EventHandler ReceiveDataEvent;
        private TcpHelper() 
        {
            service.Setup(new TouchSocketConfig()
                //.SetListenIPHosts(listenAddress)
                .ConfigureContainer(a =>
                {
                    a.AddConsoleLogger();
                })
                .ConfigurePlugins(a =>
                {
                    a.UseCheckClear()
                    .SetCheckClearType(CheckClearType.All)
                    .SetTick(TimeSpan.FromSeconds(300))
                    .SetOnClose((c, t) =>
                    {
                        c.TryShutdown();
                        c.SafeClose("超时无数据");
                    });
                }));

            service.Connecting = (client, e) => {
                Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：有客户端正在连接", "Info");
                Console.WriteLine("有客户端正在连接");
                return EasyTask.CompletedTask;
            };//有客户端正在连接
            service.Connected = (client, e) => {
                Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：客户端成功连接", "Info");
                Console.WriteLine("客户端成功连接");
                return EasyTask.CompletedTask;
            };//有客户端连接
            service.Disconnected = (client, e) => {
                foreach (var item in GPRSDevices.ToArray())
                {
                    if (item.Value.Id == client.Id)
                    {
                        GPRSDevices.Remove(item.Key);
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：客户端{item.Value.Address}断开连接", "Info");
                    }
                }
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    ObservableCollection<Device> devices = ServiceLocator.Current.GetInstance<MainViewModel>().DeviceList;
                    foreach (var item in devices.ToArray())
                    {
                        if (item.DeviceType.Equals("集中器"))
                        {
                            ServiceLocator.Current.GetInstance<MainViewModel>().DeviceList.Remove(item);
                        }
                    }
                    foreach (var item in GPRSDevices)
                    {
                        Device device = new Device() { DeviceType = "集中器", DeviceAddress = item.Value.Address };
                        ServiceLocator.Current.GetInstance<MainViewModel>().DeviceList.Add(device);
                    }
                });
                Console.WriteLine("客户端断开连接");
                return EasyTask.CompletedTask;
            };//有客户端断开连接
            service.Received = (client, e) =>
            {
                ReceiveDataEventArg arg = new ReceiveDataEventArg();
                //从服务器收到信息
                string mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);
                DateTime recvDateTime = DateTime.Now;
                //arg.Data = Convert.to
                string msgStr = "";
                //arg.Data = System.Text.Encoding.UTF8.GetBytes(mes);
                arg.Data = ByteUtils.byteTrimEnd(e.ByteBlock.Buffer);
                for (int i = 0; i < arg.Data.Length; i++)
                {
                    msgStr += arg.Data[i].ToString("X2") + " ";
                }
                Console.WriteLine($"从{client.Id}接收到信息：{msgStr}");
               
                if (ReceiveDataEvent!=null&& AnalysisMessage.GetValidFrameByte(arg.Data)!=null)
                {
                    Enums.LinkEnum link=Enums.LinkEnum.Login;
                    GPRSInfo gPRSInfo = AnalysisMessage.AnalysisGPRSLogin(arg.Data,ref link);
                    if (gPRSInfo!=null)
                    {
                        Messenger.Default.Send<string>($"接收帧({DateTime.Now.ToString()})：{msgStr}", "RecvMessage");
                        gPRSInfo.Id = client.Id;
                        switch (link)
                        {
                            case Enums.LinkEnum.Login:
                                if (GPRSDevices.ContainsKey(gPRSInfo.Address))
                                {
                                    GPRSDevices.Remove(gPRSInfo.Address);
                                }
                                else
                                {
                                    Device device = new Device { DeviceType = "集中器", DeviceAddress = gPRSInfo.Address };
                                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        ServiceLocator.Current.GetInstance<MainViewModel>().DeviceList.Add(device);
                                    });
                                }
                                Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：{gPRSInfo.Address}登录", "Info");
                                GPRSDevices.Add(gPRSInfo.Address, gPRSInfo);
                                break;
                            case Enums.LinkEnum.Heart:
                                Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：{gPRSInfo.Address}心跳", "Info");
                                GPRSDevices[gPRSInfo.Address] = gPRSInfo;
                                break;
                            default:
                                break;
                        }
                        
                        service.Send(client.Id, MessageGenerationModule.GetGPRSLinkResponseFrame(gPRSInfo, recvDateTime));
                    }
                    else
                    {
                        ReceiveDataEvent.Invoke(null, arg);
                        isComplete = true;
                    }
                    
                }
                
                return EasyTask.CompletedTask;
            };
        }
        public static TcpHelper Instance { get { return instance; } }
        private TcpService service = new TcpService();

        public int Host;

       /* public TcpHelper()
        {
            if (service == null)
            {
                service = new TcpService();
                service.Connecting = (client, e) => {
                    Console.WriteLine("有客户端正在连接");
                    return EasyTask.CompletedTask; 
                };//有客户端正在连接
                service.Connected = (client, e) => {
                    Console.WriteLine("客户端成功连接");
                    return EasyTask.CompletedTask; 
                };//有客户端连接
                service.Disconnected = (client, e) => {
                    Console.WriteLine("客户端断开连接");
                    return EasyTask.CompletedTask; 
                };//有客户端断开连接
            }
        }*/
       public void SetTCP(int listenAddress)
        {
            //service.Received =
            Host = listenAddress;
        }
        
       
        public bool OpenTCP()
        {
            
            try
            {
                service.AddListen(new TcpListenOption()
                {
                    IpHost= Host,
                });
                service.Start();
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            

        }

        public void CloseTCP()
        {
            service?.Stop();
        }
        public void SendData(string address, byte[] b)
        {
            try
            {
                GPRSInfo gPRSInfo = GPRSDevices[address];
                service.Send(gPRSInfo.Id, b);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public override string ToString()
        {
            string msg = "";
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    msg = ip.ToString();
                }
            }
            return msg;
        }
        public string GetIPAddress()
        {
            string ip = "0.0.0.0";
            try
            {
                WebClient MyWebClient = new WebClient();
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

                Byte[] pageData = MyWebClient.DownloadData("http://www.net.cn/static/customercare/yourip.asp"); //从指定网站下载数据

                string pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312，则使用这句

                int i1 = pageHtml.IndexOf("<h2>"), i2 = pageHtml.IndexOf("</h2>");
                ip = pageHtml.Substring(i1 + 1, i2 - 1 - i1);
                ip = ip.Substring(3, ip.Length - 3);
            }
            catch (WebException webEx)
            {
                webEx.Message.ToString();
            }
            return ip;
        }
    }
    /// <summary>
    /// 串口接收数据事件的参数
    /// </summary>

}
